package com.example.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.entity.Admin;
import com.example.entity.Student;
import com.example.exception.ServiceException;
import com.example.mapper.AdminMapper;
import com.example.mapper.StudentMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    StudentMapper studentMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            token = request.getParameter("token"); //url参数 ?token=xxxx parameter参数
        }
        if (handler instanceof HandlerMethod){
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (annotation != null);{
                return true;
            }
        }
        if (StrUtil.isBlank(token)){
            throw new ServiceException("401","权限错误，请登录");
        }
        String userId;
        try{
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j){
            throw new ServiceException("401","请登录");
        }
        Student studentUser = studentMapper.selectById(Integer.valueOf(userId));
        if (studentUser == null){
            throw new ServiceException("401","请登录");
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(studentUser.getPassword())).build();
        try{
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e){
            throw new ServiceException("401","请登录");
        }
        return true;
    }
}
